<template>
  <van-form @submit="onSubmit">
    <van-field
      v-model="username"
      name="用户名"
      label="用户名"
      placeholder="用户名"
      :rules="[
        { required: true, message: '请填写用户名' },
        { validator: validatorUser, message: '该用户名已经存在' },
      ]"
    />
    <van-field
      v-model="password"
      type="password"
      name="密码"
      label="密码"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
    <van-field
      v-model="secondPassword"
      type="password"
      name="确认密码"
      label="确认密码"
      placeholder="确认密码"
      :rules="[
        { required: true, message: '请填写确认密码' },
        { validator, message: '两次密码输入不一致' },
      ]"
    />
    <div style="margin: 16px">
      <van-button round block type="info" native-type="submit">注册</van-button>
    </div>
  </van-form>
</template>

<script>
import { registerApi, checkUserApi } from "../http/userApi";

export default {
  name: "RegisterForm",
  data() {
    return {
      username: "",
      password: "",
      secondPassword: "",
    };
  },
  methods: {
    validatorUser() {
      return new Promise((resolve) => {
        checkUserApi(this.username)
          .then((res) => {
            console.log(res.data.msg);
            if (res.data.code == "200") {
              resolve(true);
            } else {
              resolve(false);
            }
          })
          .catch((err) => {
            console.log("验证失败：", err);
            resolve(false);
          });
      });
    },
    validator(val) {
      if (this.password != val) {
        return false;
      } else {
        return true;
      }
    },
    onSubmit() {
      registerApi(this.username, this.password)
        .then((res) => {
          console.log("注册成功：", res.data);
          if (res.data.code == "200") {
            this.$toast.success(res.data.errMsg);
            this.$emit("changeActive", 0);
          }
        })
        .catch((err) => {
          console.log("注册失败：", err);
        });
    },
  },
};
</script>